import { Form, Row, Col, Input, Button, Select, Table, Modal, notification, Pagination } from 'antd';
import React, { useState, Fragment, useEffect } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { useRequest, useBoolean } from '@umijs/hooks';

import AuthComponent from '@/components/Authorized/AuthComponent';
import style from '../styles.less';
import { getPassengerListData, frozenPassenger } from '../../../service';
// 过滤证件类型
const flilterIDtype = (v) => {
    if (v === 'NI') {
        return (
            <span>身份证</span>
        )
    } else if (v === 'PP' || v === 'PSPT') {
        return (
            <span>护照</span>
        )
    } else {
        return (
            <span>其他</span>
        )
    }
}

const filterReceiveStatus = (v) => {
    if (v === '1') {
        return (
            <span>已领取</span>
        )
    } else if (v === '0') {
        return (
            <span>未领取</span>
        )
    } else {
        return (
            <span>领取中</span>
        )
    }
}

const filterFrozenStatus = (v) => {
    if (v === '1') {
        return (
            <span>冻结</span>
        )
    } else {
        return (
            <span>未冻结</span>
        )
    }
}
const filterPayStatus = (v) => {
    if (v === '0') {
        return  (
          <span>未支付</span>
        )
      } else if (v === '1') {
        return (
          <span>支付成功</span>
        )
      } else if (v=== '2') {
        return (
          <span>支付失败</span>
        )
      } else {
        return (
          <span>未支付</span>
        )
      }
}
const EditPassenger = props => {
    const { form: { getFieldDecorator, getFieldValue, setFieldsValue }, 
    handleModalVisible, checkedPassengerList, orderId, handelCheckedList, payType } = props;

    const newColumns = [
        {
            title: '姓名',
            dataIndex: 'psgName',
            fixed: 'left',
            width: 110,
            align: 'center',
            render: (text, record) => {
                return (
                    <div>
                        <span style={{ verticalAlign: 'middle' }}>{text || record.psgNameEn }</span>
                        {record.withBaby === "Y" ? (<img alt="" style={{ verticalAlign: 'middle' }} src={require('../../../components/images/icon-test.svg')} />) : null}
                        {record.isChild=== "Y" ? (<img alt="" style={{ verticalAlign: 'middle' }} src={require('../../../components/images/ertong.svg')} />) : null}
                    </div>
                )
            }
        },
        {
            title: '证件类型',
            dataIndex: 'idType',
            fixed: 'left',
            width: 110,
            align: 'center',
            render: text => {
                return flilterIDtype(text)
            }
        },
        {
            title: '领取状态',
            dataIndex: 'receiveStatus',
            fixed: 'left',
            width: 100,
            align: 'center',
            render: text => {
                return filterReceiveStatus(text)
            }
        },
        {
            title: '证件号',
            dataIndex: 'idNum',
            fixed: 'left',
            width: 180,
            align: 'center'
        },
        {
            title: '旅客手机号',
            ellipsis: true,
            dataIndex: 'phone',
            align: 'center',
            width: 120
        },
        {
            title: '航段',
            dataIndex: 'segment',
            width: 160,
            align: 'center'
        },
        {
            title: '补偿金额',
            dataIndex: 'currentAmount',
            width: 100,
            align: 'center'
        },
        {
            title: '购票时间',
            dataIndex: 'printTicketTime',
            align: 'center',
            width: 180
        },
        {
            title: '支付状态',
            dataIndex: 'payStatus',
            align: 'center',
            width: 120,
            render: (text) => {
                return filterPayStatus(text)
            }
        },
        {
            title: '支付失败原因',
            dataIndex: 'payFailInfo',
            align: 'center',
            width: 180,
            render:text=>{
              return text === "您申领的补偿中，存在补偿单已关闭，请重新申请" ? "" : text;
            }
        },
        {
            title: '值机状态',
            dataIndex: 'status',
            align: 'center',
            width: 130,
            render: (status) => (
                <>
                    <span style={{ display: status === 'PT' ? 'block' : 'none' }}>PT（出票）</span>
                    <span style={{ display: status === 'NA' ? 'block' : 'none' }}>NA（未值机）</span>
                    <span style={{ display: status === 'AC' ? 'block' : 'none' }}>AC（值机）</span>
                    <span style={{ display: status === 'XR' ? 'block' : 'none' }}>XR（值机取消）</span>
                    <span style={{ display: status === 'CL' ? 'block' : 'none' }}>CL（订座取消）</span>
                    <span style={{ display: status === 'SB' ? 'block' : 'none' }}>SB（候补）</span>
                    <span style={{ display: status === 'DL' ? 'block' : 'none' }}>DL（拉下）</span>
                </>
            )
        },
        {
            title: '是否冻结',
            dataIndex: 'switchOff',
            width: 100,
            align: 'center',
            render: text => {
                return filterFrozenStatus(text)
            }
        },
        {
            title: '票号',
            dataIndex: 'etNum',
            width: 140,
            align: 'center'
        },
        {
            title: '主舱位',
            dataIndex: 'mainClass',
            width: 90,
            align: 'center'
        },
        {
            title: '子舱位',
            dataIndex: 'subClass',
            width: 90,
            align: 'center'
        },
        {
            title: 'PNR',
            dataIndex: 'pnrRef',
            align: 'center',
            width: 120
        },

    ];
    const { confirm } = Modal;
    const { Option } = Select
    const [current, handleCurrent] = useState(1);
    const [pageSize, handlePageSize] = useState(1000);
    const [total, handleTotal] = useState(0);
    const [checkedMans, setCheckedMans] = useState(0)// 已选旅客人数（包含婴儿）
    const [allMans, setAllMans] = useState(0)// 全部旅客人数（包含婴儿）


    // 设置按钮的禁用 和 启用
    const { state: disBtn, setTrue, setFalse } = useBoolean(true);

    // 选中的列表的Id数组
    const [ids, handleIds] = useState([]);


    // 表格数据
    const [tableData, handleTableData] = useState(checkedPassengerList);

    const { run: searchPassenger,loading } = useRequest((params) => getPassengerListData(params), {
        manual: true,
        onSuccess: (searchPassengerData) => {
            let searchArr =  searchPassengerData.data || [];
            handleTableData(searchArr);
            handelCheckedList(searchArr);
            // handleTableData(searchPassengerData.data);
            // handelCheckedList(searchPassengerData.data);
            // handleTotal(searchPassengerData.total);
            // handleCurrent(searchPassengerData.current);
            // handlePageSize(searchPassengerData.pageSize);
        }
    })

    useEffect(() => {
        let mans = 0; //所有计算人数
        for (let item of tableData) {
            if (item.withBaby === 'Y') {
                mans+=1;
            }
        }
        setAllMans(mans + tableData.length);
    }, [tableData])

    useEffect(() => {
        searchPassenger({
            orderId: orderId,
            pageSize: pageSize,
            current: current,
            keySearch: getFieldValue('keySearch'),
            receiveStatus: getFieldValue('receiveStatus'),
            switchOff: getFieldValue('switchOff')
        })
    }, [pageSize, current])

    const { run: frozenPassengerWay } = useRequest((params) => frozenPassenger(params), {
        manual: true,
        onSuccess: () => {
            notification.success({
                message: '成功',
                duration: 3,
                description: '操作完成'
            })
            searchPassenger({
                orderId: orderId,
                pageSize: pageSize,
                current: current
            })
        }
    })

    // 搜索查询
    const searchData = (v) => {
        searchPassenger({
            orderId: orderId,
            pageSize: pageSize,
            current: 1,
            keySearch: getFieldValue('keySearch'),
            receiveStatus: getFieldValue('receiveStatus'),
            switchOff: getFieldValue('switchOff')
        })
    }

    // 冻结领取
    const frozenCollection = () => {
        confirm({
            centered: true,
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: (
                <div style={{ fontSize: "16px" }}><span style={{ color: "#ff5a5a" }}>确认操作后, 该旅客将限制对该金额的领取权限,</span> 你还要继续吗？</div>
            ),
            okText: "继续",
            cancelText: "取消",
            onOk() {
                frozenPassengerWay({
                    paxIds: ids.join(','),
                    status: '1',
                    orderId
                })
            },
            onCancel() {
            },
        });
    };
    // 取消冻结
    const cancelFrozen = () => {
        confirm({
            centered: true,
            title: '提示',
            icon: <ExclamationCircleOutlined />,
            content: (
                <div style={{ fontSize: "16px" }}><span style={{ color: "#ff5a5a" }}>确认操作后, 该旅客将恢复对该金额得领取权限,</span> 你还要继续吗？</div>
            ),
            okText: "继续",
            cancelText: "取消",
            onOk() {
                frozenPassengerWay({
                    paxIds: ids.join(','),
                    status: '0',
                    orderId
                })
            },
            onCancel() {
            },
        });
    };
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            let mans = 0; //计算人数
            for (let item of selectedRows) {
              if (item.withBaby === 'Y') {
                mans+=1;
              }
            }
            setCheckedMans(mans + selectedRows.length);
            selectedRowKeys.length > 0 ? setFalse() : setTrue();
            handleIds(selectedRowKeys);
        },
        getCheckboxProps: record => ({
            disabled: record.receiveStatus !== '0', // Column configuration not to be checked
        }),
    };
    return (
        <Fragment>
            <Form colon={false}>
                <Row gutter={16}>
                    <Col md={12} lg={6}>
                        <Form.Item label="旅客搜索">
                            {getFieldDecorator('keySearch', {
                                initialValue: ""
                            })(
                                <Input onPressEnter={searchData} placeholder="旅客姓名/证件号/票号" />
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={12} lg={6}>
                        <Form.Item label="领取状态">
                            {getFieldDecorator('receiveStatus', {
                                initialValue: ''
                            })(
                                <Select onChange={(v) => {
                                    setFieldsValue({
                                        receiveStatus: v
                                    })
                                }} placeholder="请选择状态">
                                    <Option value="">全部</Option>
                                    <Option value="0">未领取</Option>
                                    <Option value="1">已领取</Option>
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={12} lg={6}>
                        <Form.Item label="冻结状态">
                            {getFieldDecorator('switchOff', {
                                initialValue: ''
                            })(
                                <Select onChange={(v) => {
                                    setFieldsValue({
                                        switchOff: v
                                    })
                                }} placeholder="请选择状态">
                                    <Option value="">全部</Option>
                                    <Option value="0">未冻结</Option>
                                    <Option value="1">冻结</Option>
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                    <Col md={12} lg={6}>
                        <Form.Item label=" ">
                            {getFieldDecorator('option', {
                            })(
                                <Row gutter={16}>
                                    <Col lg={8} md={12}>
                                        <Button onClick={() => {
                                            searchPassenger({
                                                orderId: orderId,
                                                keySearch: getFieldValue('keySearch'),
                                                receiveStatus: getFieldValue('receiveStatus'),
                                                switchOff: getFieldValue('switchOff'),
                                                pageSize: pageSize,
                                                current: current
                                            })
                                        }} style={{ marginRight: "20px" }} type="primary">查询</Button>
                                    </Col>
                                    <Col lg={8} md={12}>
                                        <Button onClick={() => {
                                            setFieldsValue({
                                                keySearch: '',
                                                receiveStatus: '',
                                                switchOff: '',
                                            })
                                            searchPassenger({
                                                orderId: orderId,
                                                pageSize: pageSize,
                                                current: current
                                            })
                                        }}>重置</Button>
                                    </Col>
                                </Row>
                            )}
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <Table
                columns={newColumns}
                dataSource={tableData}
                loading = {loading}
                bordered
                rowSelection={rowSelection}
                pagination={false}
                scroll={{ y: 400, x: 900 }}
                rowKey="idx"
                size="small"
            />

            {/* <Pagination
                total={total}
                showSizeChanger
                showQuickJumper
                showTotal={(total, range) => `${range[0]}-${range[1]} 共 ${total} 项`} pageSize={pageSize} current={current}
                onChange={page => {
                    handleCurrent(page)
                }}
                onShowSizeChange={(current, size) => {
                    handlePageSize(size)
                }} /> */}
            <div className={style.footerToolbar}>
                <div className={style.personNum}>
                    <span style={{ textDecoration: "none" }}>{`已选${checkedMans}人`}</span>
                    <span style={{ textDecoration: "none" }}>{`共${allMans}人`}</span>
                </div>
                <AuthComponent authCode="compensation.maintain.frozen">
                    <Button disabled={disBtn} onClick={frozenCollection} style={{ marginRight: "20px" }}  type="primary">冻结领取</Button>
                </AuthComponent>
                    {payType == '0' ? null : <AuthComponent authCode="compensation.maintain.unfrozen"><Button disabled={disBtn} onClick={cancelFrozen} style={{ marginRight: "20px" }} type="primary">取消冻结</Button></AuthComponent>}
                <Button onClick={() => { handleModalVisible(false) }}>关闭</Button>
            </div>
        </Fragment>
    )
}

export default Form.create()(EditPassenger);